package com.binyouwei.reverse_development.packet_capture

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.binyouwei.reverse_development.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException

class PacketCaptureActivity : AppCompatActivity() {
    private val client = OkHttpClient()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_packet_capture)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        findViewById<Button>(R.id.bt_send_request).setOnClickListener {
            sendGetRequest()
        }
    }

    private fun sendGetRequest() {
        //1.创建一个request
        val request = Request.Builder()
            .url("https://www.wanandroid.com/chapter/547/sublist/json")
            .method("GET", null)
            .build();

        //2.创建客户端
        val client = OkHttpClient.Builder().build();

        //3.请求
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                receiveMessage("请求失败，原因：${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                val responseBody = response.body?.string()
                receiveMessage(responseBody)
            }
        });
        Thread {
        }.start()
    }

    private fun receiveMessage(content: String?) {
        val message = Message()
        message.obj = content
        handler.sendMessage(message)
    }

    private val handler = object : Handler(Looper.getMainLooper()) {
        @SuppressLint("SetTextI18n")
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val content = msg.obj as String
            findViewById<TextView>(R.id.tv_result).text = "收到请求响应信息：$content"
        }
    }
}